package com.mww.chatroom.controller;

import com.mww.chatroom.mapper.UserMapper;
import com.mww.chatroom.model.User;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Resource
    UserMapper userMapper;
    //登录
@PostMapping("/login")
    public Object login(String username, String password, HttpServletRequest request){
    //先去数据库查username能否找对象
    User user = userMapper.selectByUsername(username);
    //能找到判断密码是否匹配
    if(user==null||!user.getPassword().equals(password)){
        //登录失败返回一个空的user对象,打印user信息要使用tostring
//        System.out.println("登陆失败，用户名或者密码错误"+user.toString());
        return new User();
    }
    //都匹配登录成功，创建会话
    user.setPassword("");
    HttpSession session = request.getSession(true);
    session.setAttribute("user",user);
    return user;

    }

    //注册
    @PostMapping("/register")
    public Object register(@RequestParam("username") String username, @RequestParam("password") String password){
    User user= new User();
    try{
        user.setUsername(username);
        user.setPassword(password);
        //数据库中定义username为unique,如果username重复则会抛出异常
        int ret = userMapper.insert(user);
        System.out.println("注册ret"+ret);
        user.setPassword("");
    }catch (DuplicateKeyException e){
        //出现异常，名字重复，注册失败
       user = new User();
    }
return user;
    }

    @GetMapping("/userInfo")
    public Object userInfo(HttpServletRequest req){
    //1.先从请求中获取到会话
        HttpSession session = req.getSession(false);
        if(session==null){
            //会话不存哎，用户未登录，返回一个空的对象
            System.out.println("[getUserInfo]当前获取不到session对象!");
            return new User();
        }
        //2.从会话中获取到之前保存的用户对象
        User user = (User) session.getAttribute("user");
        if(user==null){
            System.out.println("[getUserInfo]当前获取不到user对象!");
            return new User();
        }

        user.setPassword("");
        return user;

    }
}
